package vip.ola.pay.channel.daifuchannel;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.util.MyLog;
import vip.ola.pay.batchpay.HttpClientUtil;
import vip.ola.pay.batchpay.Md5Util;
import vip.ola.pay.batchpay.PaysUtil;
import vip.ola.pay.batchpay.RSAUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
public class TestBatchPay {

    private static final MyLog _log = MyLog.getLog(TestBatchPay.class);



    public static JSONObject trans() {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String downSn = "DS" + df.format(System.currentTimeMillis());
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("name", "ceshi");
            obj.put("ka", "62258878542702222");
            obj.put("money", "1");
            obj.put("merId", PaysUtil.memberCode);
            obj.put("bank", "工商银行");
            obj.put("nonceStr", "batch123");
            obj.put("notifyUrl", "http://159.138.142.167:8403/api/trans/notify");
            obj.put("orderId", downSn);
//            obj.put("zhihang", "工商银行");
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            String sign = sign(paramsrc);
//            byte[] queryBytes;
            String queryBytes = RSAUtils.sign(sign.getBytes("UTF-8"), PaysUtil.privateKey);
//            String cipherData = Base64Utils.encode(queryBytes);
            System.out.println(queryBytes);
            obj.put("sign", queryBytes);
            _log.info("查询请求url={}，param={}",PaysUtil.url,obj);
            String respData = call(PaysUtil.url,obj);
            _log.info("query end ,the respData->{}",respData);
            JSONObject jsonObject = JSONObject.parseObject(respData);
            if (jsonObject != null) {
                String code = jsonObject.getString("code");
                if ("1".equals(code)) {
                    JSONObject dataObject = JSONObject.parseObject(jsonObject.getString("data"));
                    String orderId=dataObject.getString("orderId");

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }

    private static String sign(String paramSrc) {
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramSrc + "&key=" + PaysUtil.memberSecret);
        String sign = null;
        try {
            System.out.println("****待签名信息:"+strbuff.toString());
            sign = Md5Util.MD5Encode(strbuff.toString(), "UTF-8").toUpperCase();
            System.out.println("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }

    public static JSONObject query() {
        try {
            String downSn ="yous20210604211305";
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("merchant_sn", PaysUtil.memberCode);
            obj.put("down_sn", downSn);
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            String sign = sign(paramsrc);
            _log.info("batch pay the request is->{}",sign);
            String str = HttpClientUtil.submitPost(PaysUtil.url + "/api/settle/query",
                    "merchant_sn=" + PaysUtil.memberCode + "&down_sn=" + downSn+ "&sign=" + sign, "utf-8", 60000, 60000);
            _log.info("batch pay the res is->{}",str);
            JSONObject jsonObject = JSONObject.parseObject(str);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }



    public static void main (String args[]){
////        trans();
//        String signs="FtlR5eqZ4PaZR3vWSjRhd+1VFJhOZ8S6ceRnhhY+5n/v9UEcOw90CRU0kGZmvZTui687s90hDIb5OXqNBFK4eYZCAXUH8Yje1AMbsupKKVDYBCd4Dwlt0JcGd9PpJM7RtVj9GcK2APxe9ke//uZzZbA/Tc+E01UqsPIcK4v4KwE=";
//        TreeMap<String, String> jsonObject = new TreeMap<String, String>();
//        jsonObject.put("merId","202110151");
//        jsonObject.put("orderId","DS20211023183852");
//        jsonObject.put("nonceStr","9Mvyh6UsqEteCgcKWw1kH8jPoGIX2rYT");
////        jsonObject.put("sign","FtlR5eqZ4PaZR3vWSjRhd+1VFJhOZ8S6ceRnhhY+5n\\/v9UEcOw90CRU0kGZmvZTui687s90hDIb5OXqNBFK4eYZCAXUH8Yje1AMbsupKKVDYBCd4Dwlt0JcGd9PpJM7RtVj9GcK2APxe9ke\\/\\/uZzZbA\\/Tc+E01UqsPIcK4v4KwE=");
//        StringBuffer paramstr = new StringBuffer();
//        for (String pkey : jsonObject.keySet()) {
//            String pvalue = jsonObject.get(pkey);
//            if (pvalue != null && pvalue != "") {
//                paramstr.append(pkey + "=" + pvalue + "&");
//            }
//        }
//        String paramsrc = paramstr.substring(0, paramstr.length() - 1);
//        String sign = sign(paramsrc);
//        try{
//         Boolean flag=  RSAUtils.verify(sign.getBytes("UTF-8"), PaysUtil.pubkey,signs);
//            System.out.println(flag);
//       }catch (Exception e){
//           System.out.println(1111);
//       }

//        query();
    //    System.out.println(MD5Util.string2MD5("123456"));
//        String url ="http://payapi.gb666.net/Notify/GetNotify?income=8950&payOrderId=DS12021102414294428299&amount=10000&mchId=9326&productId=10001&paySuccTime=1635057091000&sign=80A0863AB2FC09EA60F1556212EE46F3&channelOrderNo=&backType=2&param1=&param2=&outTradeNo=2021103222321958021&status=2";
//      String resp=  PayUtil.call4Post(url);
//        System.out.println(resp);
        String money = "2.000000";
        System.out.println(BigDecimal.valueOf(Double.valueOf(money)).longValue());
    }


}
